<template>
  <!-- 登录页面的整体盒子 -->
  <div class="reg-container">
    <!-- 登录的盒子 -->
    <div class="reg-box">
      <!-- logo的盒子 -->
      <div class="title-box"></div>
      <!-- 登录的表单区域 -->
      <el-form :model="form" ref="form" :rules="rules">
        <!-- 用户名 -->
        <el-form-item prop="username">
          <el-input
            v-model="form.username"
            placeholder="请输入用户名"
            prefix-icon="el-icon-user"
          ></el-input>
        </el-form-item>
        <!-- 密码框 -->
        <el-form-item prop="password">
          <el-input
            v-model="form.password"
            type="password"
            placeholder="请输入密码"
            prefix-icon="el-icon-lock"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit" class="btn-all">
            登录
          </el-button>
          <router-link to="/reg">去注册</router-link>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import { loginApi } from '@/api/user'
export default {
  data () {
    return {
      form: {
        username: '',
        password: ''
      },
      rules: {
        // 非空校验-用户名校验
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { pattern: /^[a-zA-Z0-9]{1,10}$/, message: '用户名必须是1-10的字母数字', trigger: 'blur' }
        ],
        // 验证密码
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { pattern: /^\S{6,15}$/, message: '密码必须是6-15的非空字符', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    async onSubmit () {
      try {
        await this.$refs.form.validate()
        const { data } = await loginApi(this.form)
        console.log(data)
        if (data.code === 0) {
          this.$message.success('登录成功')
          localStorage.setItem('user', data.token)
          this.$router.push('/')
        } else {
          this.$message.error('用户名或密码错误')
        }
      } catch (error) {
        console.log(error)
      }
    }
  }
}
</script>

<style lang="less" scoped>
</style>
